package com.jf.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig=filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String charset = this.filterConfig.getInitParameter("charset");
        String contentType = this.filterConfig.getInitParameter("contentType");

        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);
        response.setContentType(contentType);

        String basePath = request.getContextPath()+"/";
        request.setAttribute("basePath",basePath);

        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }
}
